package com.example.huanhang.changzhouapp.fragment;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.huanhang.changzhouapp.R;
import com.example.huanhang.changzhouapp.activity.CreatNoticeActivity;
import com.example.huanhang.changzhouapp.adapter.ListAllAdapter;
import com.example.huanhang.changzhouapp.base.BaseLazyFragment;
import com.example.huanhang.changzhouapp.bean.ListInfo;
import com.example.huanhang.changzhouapp.bean.User;
import com.example.huanhang.changzhouapp.util.DateUtils;
import com.example.huanhang.changzhouapp.util.ThreadUtil;
import com.example.huanhang.changzhouapp.util.ToastUtil;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.gyf.barlibrary.ImmersionBar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.example.huanhang.changzhouapp.util.ConstantUtils.IS_NOTICE_PERMISSIONS;

/**
 * @author : lei
 * @desc :底部通知公告
 * @date : 2018/9/13 0013  上午 8:33.
 * 个人博客站: http://www.bestlei.top
 */

public class NoticeFragment extends BaseLazyFragment  {
    @BindView(R.id.tv_title)
    AppCompatTextView mTvTitle;
    @BindView(R.id.title)
    RelativeLayout mTitle;
    @BindView(R.id.tv_ren)
    TextView mTvRen;
    @BindView(R.id.tv_date)
    TextView mTvDate;
    @BindView(R.id.in_recycleview)
    RecyclerView mInRecycleview;
//    @BindView(R.id.in_refresh123)
//    SmartRefreshLayout mInRefresh;
    @BindView(R.id.menu_item)
    FloatingActionButton mMenuItem;
    @BindView(R.id.menu)
    FloatingActionMenu mMenu;
    List<User> nameList = new ArrayList<User>();
    private List<ListInfo> mList = new ArrayList<>();
    private ListAllAdapter mAdapter;
    private Handler workJBHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            int what = msg.what;
            switch (what) {
                case 0:
                    //失败
                    dismissWaitDialog();
                    ToastUtil.toast(getActivity(), "查询失败");
                    break;
                case 1:
                    //成功
                    dismissWaitDialog();
                    mAdapter.notifyDataSetChanged();
                    break;
                case 2:
                    dismissWaitDialog();
                    String[] mItems = new String[nameList.size() + 1];
                    for (int i = 0; i < nameList.size() + 1; i++) {
                        if (i < nameList.size()) {
                            mItems[i] = nameList.get(i).getName();
                        } else {
                            mItems[i] = "全部人员";
                        }

                    }
                    new AlertDialog.Builder(getActivity()).setTitle("选取人员")
                            .setItems(mItems, (dialog, which) -> {
                                mTvRen.setText(mItems[which]);
                                if ("全部人员".equals(mItems[which])) {
                                    initNoticeData();
                                } else {
                                    initSelectName(mItems[which]);
                                }
                            }).show();
                    break;
                case 3:
                    //选取人员后
                    dismissWaitDialog();
                    mAdapter.notifyDataSetChanged();
                    break;
                case 4:
                    //选取日期后
                    dismissWaitDialog();
                    mAdapter.notifyDataSetChanged();
                    break;
                case 5:
                    //选取日期后无数据
                    dismissWaitDialog();
                    mAdapter.setEmptyView(getEmptyView());
                    mAdapter.notifyDataSetChanged();
                    break;
            }
            return false;
        }
    });
    private String mUserPermissions;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        ImmersionBar.setTitleBar(getActivity(), mTitle);
    }

    private void initSelectName(String name) {
        showWaitDialog(getActivity(), "请稍后...");
        if (mList.size() != 0) {
            mList.clear();
        }
        ThreadUtil.runOnBackThread(() -> {
            String sql = "SELECT * FROM gonggao WHERE lccb_name='" + name + "' ORDER BY lccb_time DESC";
            try {
                ResultSet result = ThreadUtil.result(sql);
                while (result.next()) {
                    ListInfo listInfo = new ListInfo();
                    listInfo.setName(result.getString("lccb_name"));
                    listInfo.setDate(result.getString("lccb_time"));
                    listInfo.setTitle(result.getString("lccb_title"));
                    listInfo.setContent(result.getString("lccb_content"));
                    mList.add(listInfo);
                }

                if (mList.size() == 0) {
                    workJBHandler.sendMessage(workJBHandler.obtainMessage(0));
                } else {
                    workJBHandler.sendMessage(workJBHandler.obtainMessage(3));
                }
                result.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
    }

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_notice;
    }

    @Override
    protected void initData() {
        super.initData();
        mTvTitle.setText("通知公告");
//        mInRefresh.setEnableAutoLoadMore(false);
//        mInRefresh.setOnRefreshListener(this);
//        mInRefresh.setRefreshHeader(new ClassicsHeader(getActivity()));
        setAdapterData();
        mInRecycleview.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new ListAllAdapter(R.layout.item_list_layout, mList);
        mAdapter.setEmptyView(getEmptyView());
        adapterClickInfo();
        mInRecycleview.setAdapter(mAdapter);
    }

    private void setAdapterData() {
        initNoticeData();
    }

    private View getEmptyView() {
        return LayoutInflater.from(getActivity()).inflate(R.layout.empty_layout, null);
    }

    private void adapterClickInfo() {
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            ListInfo listInfo = mList.get(position);
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            LayoutInflater inflater = LayoutInflater.from(getActivity());
            View v = inflater.inflate(R.layout.dialog_layout, null);
            TextView title = v.findViewById(R.id.title);
            TextView date = v.findViewById(R.id.date);
            TextView name = v.findViewById(R.id.name);
            TextView content = v.findViewById(R.id.content);
            TextView tvok = v.findViewById(R.id.tvok);
            title.setText(listInfo.getTitle());
            date.setText(listInfo.getDate());
            name.setText(listInfo.getName());
            content.setText(listInfo.getContent());
            final Dialog dialog = builder.create();
            dialog.show();
            dialog.getWindow().setContentView(v);
            tvok.setOnClickListener(v1 -> dialog.dismiss());
        });
    }

    private void initNoticeData() {
        showWaitDialog(getActivity(), "查询中...");
        if (mList.size() != 0) {
            mList.clear();
        }
        ThreadUtil.runOnBackThread(() -> {
            String sql = "SELECT * FROM gonggao ORDER BY lccb_time DESC";
            try {
                ResultSet result = ThreadUtil.result(sql);
                while (result.next()) {
                    ListInfo listInfo = new ListInfo();
                    listInfo.setName(result.getString("lccb_name"));
                    listInfo.setDate(result.getString("lccb_time"));
                    listInfo.setTitle(result.getString("lccb_title"));
                    listInfo.setContent(result.getString("lccb_content"));
                    mList.add(listInfo);
                }

                if (mList.size() == 0) {
                    workJBHandler.sendMessage(workJBHandler.obtainMessage(0));
                } else {
                    workJBHandler.sendMessage(workJBHandler.obtainMessage(1));
                }
                result.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    @OnClick({R.id.tv_ren, R.id.tv_date,R.id.menu_item})
    public void viewOnClick(View v) {
        switch (v.getId()) {
            case R.id.tv_ren:
                initNameData();
                mTvDate.setText("按日期");
                break;
            case R.id.tv_date:
                mTvRen.setText("按发布人");
                new DatePickerDialog(getActivity(), 0, (view, year, month, dayOfMonth) -> {
                    String mouth = DateUtils.isOneLengthMouth(month + 1);
                    String day = DateUtils.isOneLengthDay(dayOfMonth);
                    mTvDate.setText(year + "-" + mouth + "-" + day);
                    initSelectDate(mTvDate.getText().toString());
                }, DateUtils.getCurrentYear(), DateUtils.getCurrentMonth() - 1, DateUtils.getCurrentDay())
                        .show();
                break;
            case R.id.menu_item:
                if (IS_NOTICE_PERMISSIONS.equals(mUserPermissions)) {
                    //  0  有新建通知公告的权限
                    Intent intent = new Intent(getActivity(), CreatNoticeActivity.class);
                    startActivity(intent);
                    mMenu.close(true);

                } else {
                 ToastUtil.toast(getActivity(),"无权限");
                }
                break;
        }
    }

    private void initNameData() {
        showWaitDialog(getActivity(), "请稍后...");
        if (nameList.size() != 0) {
            nameList.clear();
        }
        ThreadUtil.runOnBackThread(() -> {
            String sql = "SELECT distinct  lccb_name FROM gonggao";
            try {
                ResultSet result = ThreadUtil.result(sql);
                while (result.next()) {
                    User user = new User();
                    user.setName(result.getString("lccb_name"));
                    nameList.add(user);
                }
                if (nameList.size() == 0) {
                    workJBHandler.sendMessage(workJBHandler.obtainMessage(0));
                } else {
                    workJBHandler.sendMessage(workJBHandler.obtainMessage(2));
                }
                result.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private void initSelectDate(String date) {
        showWaitDialog(getActivity(), "查询中...");
        if (mList.size() != 0) {
            mList.clear();
        }
        Log.e("ASD", "initSelectDate: " + date);
        ThreadUtil.runOnBackThread(() -> {
            String sql = "SELECT * FROM gonggao WHERE LEFT(lccb_time,10)='" + date + "' ORDER BY lccb_time DESC";
            try {
                ResultSet result = ThreadUtil.result(sql);
                while (result.next()) {
                    ListInfo listInfo = new ListInfo();
                    listInfo.setName(result.getString("lccb_name"));
                    listInfo.setDate(result.getString("lccb_time"));
                    listInfo.setTitle(result.getString("lccb_title"));
                    listInfo.setContent(result.getString("lccb_content"));
                    mList.add(listInfo);
                }

                if (mList.size() == 0) {
                    //失败
                    workJBHandler.sendMessage(workJBHandler.obtainMessage(5));
                } else {
                    workJBHandler.sendMessage(workJBHandler.obtainMessage(4));
                }
                result.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventMainThread(User user) {
        mUserPermissions = user.getPermissions();

    }
//    @Override
//    public void onRefresh(RefreshLayout refreshLayout) {
//        initNoticeData();
//        mTvDate.setText("按日期");
//        mTvRen.setText("按发布人");
//        mInRefresh.finishRefresh();
//    }
}
